from django.shortcuts import render
from django.db.models import Q
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from rest_framework import mixins
from rest_framework import viewsets
from .serializers import SmsSerializer, UserRegSerializer, UserDetailSerializer
from utils.yunpian import YunPian, API_KEY
from random import choice
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler
from .models import VerifyCode
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework import permissions, authentication
User = get_user_model()

# Create your views here.


class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class SmsCodeViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    """
    create:
        发送短信验证码
    """
    serializer_class = SmsSerializer

    def generate_code(self):
        """
        生成四位数字的验证码
        :return:
        """
        code = ""
        seeds = "9876543210123456789"
        for i in range(4):
            code += choice(seeds)
        return code

    def create(self, request, *args, **kwargs):
        # print(request.META['CONTENT_TYPE'])获取请求头
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        mobile = serializer.validated_data['mobile']
        yun_pian = YunPian(API_KEY)
        code = self.generate_code()
        sms_send_status = yun_pian.send_sms(code=code, mobile=mobile)
        if sms_send_status['code'] == 0:
            VerifyCode(
                mobile=mobile,
                code=code,
            ).save()
            return Response({"mobile": sms_send_status['msg']}, status=status.HTTP_201_CREATED)
        else:
            return Response({"mobile": sms_send_status['msg']}, status=status.HTTP_400_BAD_REQUEST)


class UserViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.UpdateModelMixin):
    """
    create:
    用户注册
    retrieve:
    用户详情信息
    update:
    用户信息修改
    """
    # serializer_class = UserRegSerializer
    queryset = User.objects.all()
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)

    def get_permissions(self):
        if self.action == 'retrieve':
            return [permissions.IsAuthenticated()]
        elif self.action == 'create':
            return []
        return []

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return UserDetailSerializer
        elif self.action == 'create':
            return UserRegSerializer
        return UserDetailSerializer

    def get_object(self):
        return self.request.user

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        payload = jwt_payload_handler(user)
        re_dict = serializer.data
        re_dict['token'] = jwt_encode_handler(payload)
        re_dict['name'] = user.name if user.name else user.username
        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()
